import axios from "axios";
import store from "@/store";
import { ElMessage } from "element-plus";
import { isCheckTimeout } from "@/utils/auth";
import md5 from "md5";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    const { icode, time } = getTestICode();
    config.headers.icode = icode;
    config.headers.codeType = time;
    // 如果有token 请求头统一注入token
    if (store.getters.token) {
      // 登录超时退出
      if (isCheckTimeout()) {
        store.dispatch("user/logout");
        return Promise.reject(new Error("token 失效"));
      }
      config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    // 配置接口国际化
    config.headers["Accept-Language"] = store.getters.language;

    return config; // 必须返回配置
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { success, message, data } = response.data;
    //   要根据success的成功与否决定下面的操作
    if (success) {
      return data;
    } else {
      // 业务错误
      ElMessage.error(message); // 提示错误消息
      return Promise.reject(new Error(message));
    }
  },
  (error) => {
    // 处理 token 超时问题
    if (error.response && error.response.data && error.response.data.code === 401) {
      // token超时
      store.dispatch("user/logout");
    }
    ElMessage.error(error.message); // 提示错误信息
    return Promise.reject(error);
  }
);

/**
 * 返回 Icode 的实现
 */
function getTestICode() {
  const now = parseInt(Date.now() / 1000);
  const code = now + "LGD_Sunday-1991";
  return {
    icode: md5(code),
    time: now,
  };
}

export default service;
